<template>
  <div class="match-create-container">
    <el-card class="form-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">创建比赛</span>
          <el-button @click="$router.back()">
            <IconifyIconOffline icon="ep:back" class="mr-1" />
            返回
          </el-button>
        </div>
      </template>

      <el-form
        ref="matchFormRef"
        :model="matchForm"
        :rules="matchRules"
        label-width="120px"
        class="match-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="比赛名称" prop="name">
                <el-input
                  v-model="matchForm.name"
                  placeholder="请输入比赛名称"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="副标题" prop="subtitle">
                <el-input
                  v-model="matchForm.subtitle"
                  placeholder="请输入副标题"
                  maxlength="100"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="运动类型" prop="sportType">
                <el-select
                  v-model="matchForm.sportType"
                  placeholder="选择运动类型"
                >
                  <el-option label="篮球" value="basketball" />
                  <el-option label="羽毛球" value="badminton" />
                  <el-option label="足球" value="football" />
                  <el-option label="网球" value="tennis" />
                  <el-option label="乒乓球" value="pingpong" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="比赛级别" prop="level">
                <el-select v-model="matchForm.level" placeholder="选择比赛级别">
                  <el-option label="国际级" value="international" />
                  <el-option label="国家级" value="national" />
                  <el-option label="省级" value="provincial" />
                  <el-option label="市级" value="city" />
                  <el-option label="区级" value="district" />
                  <el-option label="业余级" value="amateur" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="比赛类型" prop="matchType">
                <el-select
                  v-model="matchForm.matchType"
                  placeholder="选择比赛类型"
                >
                  <el-option label="单淘汰赛" value="single_elimination" />
                  <el-option label="双淘汰赛" value="double_elimination" />
                  <el-option label="循环赛" value="round_robin" />
                  <el-option label="瑞士制" value="swiss" />
                  <el-option label="积分赛" value="points" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="比赛描述" prop="description">
            <el-input
              v-model="matchForm.description"
              type="textarea"
              :rows="4"
              placeholder="请输入比赛描述"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="比赛封面">
            <el-upload
              class="cover-uploader"
              :show-file-list="false"
              :on-success="handleCoverSuccess"
              :before-upload="beforeCoverUpload"
              action="#"
            >
              <img
                v-if="matchForm.cover"
                :src="matchForm.cover"
                class="cover-image"
              />
              <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">
              建议尺寸：400x300px，支持jpg、png格式，大小不超过2MB
            </div>
          </el-form-item>
        </div>

        <!-- 时间安排 -->
        <div class="form-section">
          <h3 class="section-title">时间安排</h3>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="报名开始时间" prop="registrationStartDate">
                <el-date-picker
                  v-model="matchForm.registrationStartDate"
                  type="datetime"
                  placeholder="选择报名开始时间"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="报名结束时间" prop="registrationEndDate">
                <el-date-picker
                  v-model="matchForm.registrationEndDate"
                  type="datetime"
                  placeholder="选择报名结束时间"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="比赛开始时间" prop="startDate">
                <el-date-picker
                  v-model="matchForm.startDate"
                  type="datetime"
                  placeholder="选择比赛开始时间"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="比赛结束时间" prop="endDate">
                <el-date-picker
                  v-model="matchForm.endDate"
                  type="datetime"
                  placeholder="选择比赛结束时间"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 地点信息 -->
        <div class="form-section">
          <h3 class="section-title">地点信息</h3>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="省份" prop="province">
                <el-select
                  v-model="matchForm.province"
                  placeholder="选择省份"
                  @change="handleProvinceChange"
                >
                  <el-option label="广东省" value="广东省" />
                  <el-option label="北京市" value="北京市" />
                  <el-option label="上海市" value="上海市" />
                  <el-option label="浙江省" value="浙江省" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="城市" prop="city">
                <el-select
                  v-model="matchForm.city"
                  placeholder="选择城市"
                  @change="handleCityChange"
                >
                  <el-option label="深圳市" value="深圳市" />
                  <el-option label="广州市" value="广州市" />
                  <el-option label="东莞市" value="东莞市" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="区县" prop="district">
                <el-select v-model="matchForm.district" placeholder="选择区县">
                  <el-option label="南山区" value="南山区" />
                  <el-option label="福田区" value="福田区" />
                  <el-option label="罗湖区" value="罗湖区" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="详细地址" prop="address">
                <el-input
                  v-model="matchForm.address"
                  placeholder="请输入详细地址"
                  maxlength="100"
                  show-word-limit
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="场馆名称" prop="venue">
                <el-input
                  v-model="matchForm.venue"
                  placeholder="请输入场馆名称"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 参赛设置 -->
        <div class="form-section">
          <h3 class="section-title">参赛设置</h3>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="最大队伍数" prop="maxTeams">
                <el-input-number
                  v-model="matchForm.maxTeams"
                  :min="2"
                  :max="128"
                  placeholder="最大队伍数"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="每队人数" prop="teamSize">
                <el-input-number
                  v-model="matchForm.teamSize"
                  :min="1"
                  :max="20"
                  placeholder="每队人数"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="报名费" prop="registrationFee">
                <el-input-number
                  v-model="matchForm.registrationFee"
                  :min="0"
                  :precision="2"
                  placeholder="报名费（元）"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="参赛资格" prop="eligibility">
                <el-select
                  v-model="matchForm.eligibility"
                  placeholder="选择参赛资格"
                >
                  <el-option label="不限" value="unlimited" />
                  <el-option label="业余选手" value="amateur" />
                  <el-option label="专业选手" value="professional" />
                  <el-option label="学生" value="student" />
                  <el-option label="企业员工" value="employee" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="年龄限制" prop="ageLimit">
                <el-input
                  v-model="matchForm.ageLimit"
                  placeholder="如：18-35岁"
                  maxlength="20"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="性别限制" prop="genderLimit">
                <el-select
                  v-model="matchForm.genderLimit"
                  placeholder="选择性别限制"
                >
                  <el-option label="不限" value="unlimited" />
                  <el-option label="男性" value="male" />
                  <el-option label="女性" value="female" />
                  <el-option label="混合" value="mixed" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 主办方信息 -->
        <div class="form-section">
          <h3 class="section-title">主办方信息</h3>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="主办方" prop="organizer">
                <el-input
                  v-model="matchForm.organizer"
                  placeholder="请输入主办方名称"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="协办方">
                <el-input
                  v-model="matchForm.coOrganizer"
                  placeholder="请输入协办方名称（可选）"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="联系人" prop="contactName">
                <el-input
                  v-model="matchForm.contactName"
                  placeholder="请输入联系人姓名"
                  maxlength="20"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input
                  v-model="matchForm.contactPhone"
                  placeholder="请输入联系电话"
                  maxlength="20"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="联系邮箱">
                <el-input
                  v-model="matchForm.contactEmail"
                  placeholder="请输入联系邮箱（可选）"
                  maxlength="50"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 比赛规则 -->
        <div class="form-section">
          <h3 class="section-title">比赛规则</h3>

          <el-form-item label="比赛规则" prop="rules">
            <el-input
              v-model="matchForm.rules"
              type="textarea"
              :rows="6"
              placeholder="请输入详细的比赛规则"
              maxlength="1000"
              show-word-limit
            />
          </el-form-item>
        </div>

        <!-- 奖项设置 -->
        <div class="form-section">
          <h3 class="section-title">奖项设置</h3>

          <div class="prizes-container">
            <div
              v-for="(prize, index) in matchForm.prizes"
              :key="index"
              class="prize-item"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item
                    :label="`奖项${index + 1}名称`"
                    :prop="`prizes.${index}.name`"
                  >
                    <el-input
                      v-model="prize.name"
                      placeholder="如：冠军、亚军"
                      maxlength="20"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item
                    :label="`奖项${index + 1}描述`"
                    :prop="`prizes.${index}.description`"
                  >
                    <el-input
                      v-model="prize.description"
                      placeholder="如：奖杯 + 奖金5000元"
                      maxlength="100"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="4">
                  <el-button
                    type="danger"
                    :disabled="matchForm.prizes.length <= 1"
                    @click="removePrize(index)"
                  >
                    删除
                  </el-button>
                </el-col>
              </el-row>
            </div>

            <el-button
              type="primary"
              :disabled="matchForm.prizes.length >= 10"
              @click="addPrize"
            >
              <IconifyIconOffline icon="ep:plus" class="mr-1" />
              添加奖项
            </el-button>
          </div>
        </div>

        <!-- 其他设置 -->
        <div class="form-section">
          <h3 class="section-title">其他设置</h3>

          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item>
                <el-checkbox v-model="matchForm.allowSubstitute"
                  >允许替补</el-checkbox
                >
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item>
                <el-checkbox v-model="matchForm.allowSpectator"
                  >允许观众</el-checkbox
                >
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item>
                <el-checkbox v-model="matchForm.isPublic">公开比赛</el-checkbox>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item>
                <el-checkbox v-model="matchForm.needApproval"
                  >需要审核</el-checkbox
                >
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <el-button @click="$router.back()">取消</el-button>
          <el-button type="primary" :loading="submitting" @click="handleSubmit">
            创建比赛
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import { Plus } from "@element-plus/icons-vue";

const router = useRouter();

// 表单引用
const matchFormRef = ref();

// 提交状态
const submitting = ref(false);

// 比赛表单数据
const matchForm = reactive({
  name: "",
  subtitle: "",
  sportType: "",
  level: "",
  matchType: "",
  description: "",
  cover: "",
  registrationStartDate: "",
  registrationEndDate: "",
  startDate: "",
  endDate: "",
  province: "",
  city: "",
  district: "",
  address: "",
  venue: "",
  maxTeams: 16,
  teamSize: 2,
  registrationFee: 0,
  eligibility: "unlimited",
  ageLimit: "",
  genderLimit: "unlimited",
  organizer: "",
  coOrganizer: "",
  contactName: "",
  contactPhone: "",
  contactEmail: "",
  rules: "",
  prizes: [
    { name: "冠军", description: "" },
    { name: "亚军", description: "" },
    { name: "季军", description: "" }
  ],
  allowSubstitute: false,
  allowSpectator: true,
  isPublic: true,
  needApproval: false
});

// 表单验证规则
const matchRules = {
  name: [{ required: true, message: "请输入比赛名称", trigger: "blur" }],
  sportType: [{ required: true, message: "请选择运动类型", trigger: "change" }],
  level: [{ required: true, message: "请选择比赛级别", trigger: "change" }],
  matchType: [{ required: true, message: "请选择比赛类型", trigger: "change" }],
  description: [{ required: true, message: "请输入比赛描述", trigger: "blur" }],
  registrationStartDate: [
    { required: true, message: "请选择报名开始时间", trigger: "change" }
  ],
  registrationEndDate: [
    { required: true, message: "请选择报名结束时间", trigger: "change" }
  ],
  startDate: [
    { required: true, message: "请选择比赛开始时间", trigger: "change" }
  ],
  endDate: [
    { required: true, message: "请选择比赛结束时间", trigger: "change" }
  ],
  province: [{ required: true, message: "请选择省份", trigger: "change" }],
  city: [{ required: true, message: "请选择城市", trigger: "change" }],
  district: [{ required: true, message: "请选择区县", trigger: "change" }],
  address: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
  venue: [{ required: true, message: "请输入场馆名称", trigger: "blur" }],
  maxTeams: [{ required: true, message: "请输入最大队伍数", trigger: "blur" }],
  teamSize: [{ required: true, message: "请输入每队人数", trigger: "blur" }],
  organizer: [{ required: true, message: "请输入主办方", trigger: "blur" }],
  contactName: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  contactPhone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur"
    }
  ],
  rules: [{ required: true, message: "请输入比赛规则", trigger: "blur" }]
};

// 省份变化
const handleProvinceChange = () => {
  matchForm.city = "";
  matchForm.district = "";
};

// 城市变化
const handleCityChange = () => {
  matchForm.district = "";
};

// 封面上传成功
const handleCoverSuccess = (response: any) => {
  // 这里应该处理上传成功的响应
  matchForm.cover =
    "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=sports%20tournament%20poster%2C%20competition%20event%2C%20professional%20design&image_size=portrait_4_3";
  ElMessage.success("封面上传成功");
};

// 封面上传前验证
const beforeCoverUpload = (file: File) => {
  const isJPGOrPNG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPGOrPNG) {
    ElMessage.error("封面只能是 JPG/PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("封面大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 添加奖项
const addPrize = () => {
  if (matchForm.prizes.length < 10) {
    matchForm.prizes.push({ name: "", description: "" });
  }
};

// 删除奖项
const removePrize = (index: number) => {
  if (matchForm.prizes.length > 1) {
    matchForm.prizes.splice(index, 1);
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!matchFormRef.value) return;

  try {
    await matchFormRef.value.validate();

    // 验证时间逻辑
    if (
      new Date(matchForm.registrationStartDate) >=
      new Date(matchForm.registrationEndDate)
    ) {
      ElMessage.error("报名开始时间必须早于报名结束时间");
      return;
    }

    if (
      new Date(matchForm.registrationEndDate) > new Date(matchForm.startDate)
    ) {
      ElMessage.error("报名结束时间必须早于比赛开始时间");
      return;
    }

    if (new Date(matchForm.startDate) >= new Date(matchForm.endDate)) {
      ElMessage.error("比赛开始时间必须早于比赛结束时间");
      return;
    }

    submitting.value = true;

    // 这里应该调用API创建比赛
    await new Promise(resolve => setTimeout(resolve, 2000));

    ElMessage.success("比赛创建成功");
    router.push("/match/list");
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    submitting.value = false;
  }
};
</script>

<style scoped lang="scss">
.match-create-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.form-card {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }
}

.match-form {
  .form-section {
    margin-bottom: 40px;

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      margin: 0 0 20px 0;
      padding-bottom: 8px;
      border-bottom: 2px solid #409eff;
    }
  }

  .cover-uploader {
    .cover-image {
      width: 200px;
      height: 150px;
      object-fit: cover;
      border-radius: 6px;
    }

    .cover-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 200px;
      height: 150px;
      text-align: center;
      line-height: 150px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      transition: border-color 0.3s;

      &:hover {
        border-color: #409eff;
      }
    }
  }

  .upload-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
  }

  .prizes-container {
    .prize-item {
      margin-bottom: 16px;
      padding: 16px;
      background-color: #f8f9fa;
      border-radius: 6px;
      border-left: 4px solid #409eff;
    }
  }

  .form-actions {
    text-align: center;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;

    .el-button {
      min-width: 120px;
      margin: 0 10px;
    }
  }
}

@media (max-width: 768px) {
  .match-create-container {
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .match-form {
    .el-col {
      margin-bottom: 16px;
    }

    .cover-uploader {
      .cover-image,
      .cover-uploader-icon {
        width: 150px;
        height: 112px;
        line-height: 112px;
      }
    }

    .form-actions {
      .el-button {
        width: 100%;
        margin: 8px 0;
      }
    }
  }
}
</style>
